package com.bird.pro.ctrl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bird.pro.Page;
import com.bird.pro.Params;
import com.bird.pro.pojo.BirdAdmin;
import com.bird.pro.service.IAdminService;
import com.bird.pro.utils.Md5;

@Controller
@RequestMapping("admin")
public class AdminController {

	
	@Autowired
	private IAdminService adminService;
	
	@RequestMapping("main")
	public String adminMain(){
		
		return "admin/main";
	}
	
	@RequestMapping("list")
	public String adminList(Params params, Model model){
		Page page = adminService.queryByParams(params, 1);
		model.addAttribute("page", page);
		return "admin/list";
	}
	
	@RequestMapping("save")
	@ResponseBody
	public String save(BirdAdmin admin){
		if (StringUtils.isBlank(admin.getAdminAccount()) || StringUtils.isBlank(admin.getAdminPassword())) {
			return "";
		}
		List<BirdAdmin> admins = adminService.queryAdmins(admin.getAdminName(), admin.getAdminPhone(), admin.getAdminAccount());
		if (!admins.isEmpty()) {
			return "fail";
		}
		String pass = admin.getAdminPassword();
		admin.setAdminPassword(Md5.getMD5(pass));
		admin.setCreateTime(new Date());
		admin.setAdminState("1");
		int result = adminService.saveAdmin(admin);
		if (result > 0) {
			return "success";
		}
		return "";
	}
	
	@RequestMapping("update")
	@ResponseBody
	public String update(BirdAdmin admin){
		if (StringUtils.isNotBlank(admin.getAdminPassword())) {
			admin.setAdminPassword(Md5.getMD5(admin.getAdminPassword()));
		}
		int result = adminService.updateAdmin(admin);
		if (result > 0) {
			return "success";
		}
		return "";
	}
}
